package com.pentofab.payrollmanagement.ui.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.AttendanceDao;
import com.pentofab.payrollmanagement.dao.EmployeeDao;
import com.pentofab.payrollmanagement.dao.model.Attendance;
import com.pentofab.payrollmanagement.dao.model.AttendanceLeaveDetail;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.Department;
import com.pentofab.payrollmanagement.dao.model.Employee;
import com.pentofab.payrollmanagement.dao.model.Units;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;
import com.pentofab.payrollmanagement.exception.BusinessException;
import com.pentofab.payrollmanagement.utilities.CustomTableConstants;
import com.pentofab.payrollmanagement.utilities.PayRollUtility;

public class DisplayAttendanceControler extends AbstractUIController implements FormValidator,Initializable {
	
	@FXML
	TextField importFileLoc;
	@FXML
	TextField exportFileLoc;
	@FXML
	Parent root;
	@FXML
    private Button Add;
	@FXML
    private Button delete; 
	@FXML
    private Button modify;
	@FXML
    private Button cancel;
	@FXML
    private Button save;
	@FXML
    private ChoiceBox<String> department;
	@FXML
    private ChoiceBox<String> companyBox;
	@FXML
    private ChoiceBox<String> unitBox;
	@FXML
    private TextField empId; 
	@FXML
    private ChoiceBox<String> from_date; 
	@FXML
    private ChoiceBox<String> from_month; 
	@FXML
    private ChoiceBox<String> from_year; 
	@FXML
    private ChoiceBox<String> mode; 
	@FXML
    private GridPane grid; 
	@FXML
    private ChoiceBox<String> to_date; 
	@FXML
    private ChoiceBox<String> to_month; 
	@FXML
    private ChoiceBox<String> to_year; 
	@FXML
    private Button getDetails;
	@FXML
    private TableView<AttendanceLeaveDetail> displayTable; 
	@FXML
    private TableColumn<AttendanceLeaveDetail, String> eid; 
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> empName; 
	@FXML
    private TableColumn<AttendanceLeaveDetail, String> company;
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> deptCol;
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> attDate; 
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> from_time; 
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> to_time; 
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> total; 
	@FXML
	private TableColumn<AttendanceLeaveDetail, String> reson; 
	@FXML
	private ChoiceBox<String> toAdd_year;
	@FXML
	private ChoiceBox<String> toAdd_Month;
	@FXML
	private ChoiceBox<String> toAdd_date;
	@FXML
	private CheckBox firstIn_toAdd;
	@FXML
	private TextField inTime_toAdd;
	@FXML
	private CheckBox lastOut_toAdd;
    @FXML
    private TextField outTime_toAdd;
    
    boolean addEntry = false;
    boolean modifyEntry = false;
   
    private Company currCompany;
    private UserAccounts userAccounts;
	
	private ArrayList<String> yearList = new ArrayList<String>();
	private ArrayList<String> fromMonthDaysList = new ArrayList<String>();
	private ArrayList<String> toMonthDaysList = new ArrayList<String>();
	private ArrayList<String> toAddMonthDaysList = new ArrayList<String>();
	private Employee employee = null;
	int fromMaxDay;
	int toMaxDay;
	int toAddMaxDay;
	String fromDate = null;
	String toDate = null;
	EmployeeDao employeeDao = PayrollApplicationFactory.getEmployeeMgmt();
	AttendanceDao attendanceDao = PayrollApplicationFactory.getAttandanceMgmt();
	ArrayList<HashMap<String,String>> attlevDetailList = null;
	
	ArrayList<AttendanceLeaveDetail> attLeaveList = null;
	
	AttendanceLeaveDetail detailObjetAddOrMod = null;

	public void add(ActionEvent event) {
		System.out.println("======");
		if(mode.getSelectionModel().getSelectedIndex() != 0){
			showInfo(UIMessages.SELECT_DAILY_VIEW);
			moveFocusToComp(mode);
			return;
		}
		enableDisableAdd(false);
		
		moveFocusToComp(toAdd_year);
		addEntry = true;
		
	}
	
	public void save(ActionEvent event) {
		
		
		if(addEntry){
			
			String date = toAdd_date.getSelectionModel().getSelectedItem()+"-"+
					(toAdd_Month.getSelectionModel().getSelectedIndex()+1)+"-"+
					toAdd_year.getSelectionModel().getSelectedItem();
			
			try{
			if(PayRollUtility.compareDateWithToday(date) > 1){
				showError(String.format(UIMessages.TO_DATE_LATER_THAN_TODAY,date));
			}
			String inTime = inTime_toAdd.getText().trim();
			inTime = inTime.replace(".", ":");
			
			if(!inTime.contains(":")){
				showError("Invalid login time.Corrct format is (XX:YY or XX.YY)");
				inTime_toAdd.clear();
				moveFocusToComp(inTime_toAdd);
				return;
				
			}
			
			if (inTime.equals("")) {
				showInfo(UIMessages.LOG_IN_TIME_CANT_BE_EMPTY_OR_NULL);
				inTime_toAdd.setText(detailObjetAddOrMod.getFrom_time());
				moveFocusToComp(inTime_toAdd);
				return;
			}
			
			String outTime = outTime_toAdd.getText().trim();
			outTime = outTime.replace(".", ":");
			
			if(!outTime.contains(":")){
				showError("Invalid logout time.Corrct format is (XX:YY or XX.YY)");
				outTime_toAdd.clear();
				moveFocusToComp(outTime_toAdd);
				return;
				
			}
			if (outTime.equals("")) {
				showInfo(UIMessages.LOG_IN_TIME_CANT_BE_EMPTY_OR_NULL);
				outTime_toAdd.setText(detailObjetAddOrMod.getTo_time());
				moveFocusToComp(outTime_toAdd);
				return;
			}
			
			if((inTime.trim().length() != 5 || !inTime.matches("[0-9]{2}:[0-9]{2}"))){
				showError("Invlid login Time, Please enter time in XX:YY or XX.YY format");
				return;
			}
			
			if((outTime.trim().length() != 5 || !outTime.matches("[0-9]{2}:[0-9]{2}"))){
				showError("Invlid logout Time, Please enter time in XX:YY or XX.YY format");
				return;
			}
			
			int rowRowNum = 1;
			
			date = PayRollUtility.convertDateToString(PayRollUtility.convertStringToDate(date));
			
			System.out.println("date to fetch Att : "+date);
			
			ArrayList<Attendance> attInfoList = attendanceDao.getAttandaceInfo(empId.getText(),date);
			
			System.out.println("attendanceDao for modify/ add : "+attInfoList);
			if(attInfoList != null){
				
				
				if(lastOut_toAdd.isSelected()){
					
					rowRowNum = attInfoList.get(attInfoList.size()-1).getRownumber()+1;
					
					attendanceDao.updateLogOutStatus(employee.getEmpId(), date, false);
					attendanceDao.addAttandeanceEntry(employee.getEmpId(), PayRollUtility.convertStringToDate(date), 
							inTime, outTime,userAccounts.getUsername(),rowRowNum, firstIn_toAdd.isSelected(), lastOut_toAdd.isSelected());
				}else if(firstIn_toAdd.isSelected()){
					
					for(int i = attInfoList.size()-1; i >= 0; i-- ){
						
						Attendance current = attInfoList.get(i);
						
						attendanceDao.updateRowNum(i+1,employee.getEmpId(), current.getLoginTime(), current.getLogoutTime(), date);
						
					}
					attendanceDao.addAttandeanceEntry(employee.getEmpId(), PayRollUtility.convertStringToDate(date), 
							inTime, outTime,userAccounts.getUsername(),rowRowNum, firstIn_toAdd.isSelected(), lastOut_toAdd.isSelected());
				}else{
					
					Attendance current = attInfoList.get(attInfoList.size()-1);
					attendanceDao.updateRowNum(current.getRownumber()+1,employee.getEmpId(), current.getLoginTime(), current.getLogoutTime(),date);
					
					attendanceDao.addAttandeanceEntry(employee.getEmpId(), PayRollUtility.convertStringToDate(date), 
							inTime, outTime,userAccounts.getUsername(),current.getRownumber(), firstIn_toAdd.isSelected(), lastOut_toAdd.isSelected());
				}
				
			}else{
				attendanceDao.addAttandeanceEntry(employee.getEmpId(), PayRollUtility.convertStringToDate(date), 
					inTime, outTime,userAccounts.getUsername(),1, firstIn_toAdd.isSelected(), lastOut_toAdd.isSelected());
			}
			addEntry = false;

			showInfo(UIMessages.ATTENDANCE_ENTRY_ADDED_SUCCESSFULLY);
			}catch(BusinessException be){
				showError(be.getMessage());
			}catch(Exception be){
				showError(UIMessages.ERROW_WHILE_ADDING_ATTENDANCE);
			}
		}
		
		if(modifyEntry){
			try {

				if (detailObjetAddOrMod == null) {
					return;
				}

				String inTime = inTime_toAdd.getText().trim();
				inTime = inTime.replace(".", ":");
				
				if(!inTime.contains(":")){
					showError("Invalid login time.Corrct format is (XX:YY or XX.YY)");
					inTime_toAdd.clear();
					moveFocusToComp(inTime_toAdd);
					return;
					
				}
				
				if (inTime.equals("")) {
					showInfo(UIMessages.LOG_IN_TIME_CANT_BE_EMPTY_OR_NULL);
					inTime_toAdd.setText(detailObjetAddOrMod.getFrom_time());
					moveFocusToComp(inTime_toAdd);
					return;
				}

				String outTIme = outTime_toAdd.getText().trim();
				outTIme = outTIme.replace(".", ":");
				
				if(!outTIme.contains(":")){
					showError("Invalid logout time.Corrct format is (XX:YY or XX.YY)");
					outTime_toAdd.clear();
					moveFocusToComp(outTime_toAdd);
					return;
					
				}
				if (outTIme.equals("")) {
					
					showInfo(UIMessages.LOG_IN_TIME_CANT_BE_EMPTY_OR_NULL);
					outTime_toAdd.setText(detailObjetAddOrMod.getTo_time());
					moveFocusToComp(outTime_toAdd);
					return;
				}
				
				attendanceDao.modifyAttendance(detailObjetAddOrMod.getEid(),
						detailObjetAddOrMod.getAttDate(), inTime,
						firstIn_toAdd.isSelected(), outTIme,
						lastOut_toAdd.isSelected(),
						detailObjetAddOrMod.getRownum());
				modifyEntry = false;

				detailObjetAddOrMod = null;
				displayTable.getItems().clear();
				getDetails(event);
				showInfo(UIMessages.ATTENDANCE_ENTRY_MODIFIED_SUCCESSFULLY);
				
				
				System.out.println("detailObjetAddOrMod : "+ detailObjetAddOrMod);
				System.out.println("save done");

			}catch(Exception e){
			e.printStackTrace();
			showError(UIMessages.ERROW_WHILE_MODIFYING_ATTENDANCE);
			
		}
		}
		getDetails(event);
		cancel();
	}

	public void delete(ActionEvent event) {
		
		
		if(mode.getSelectionModel().getSelectedIndex() != 0){
			showInfo(UIMessages.SELECT_DAILY_VIEW);
			moveFocusToComp(mode);
			return;
		}
		if(displayTable.getSelectionModel().getSelectedIndex() < 0){
			showInfo(UIMessages.SELECT_ATTENDANCE_ENTRY_TO_MODIFY);
			moveFocusToComp(displayTable);
			return;
		}
		AttendanceLeaveDetail detail  = displayTable.getSelectionModel().getSelectedItem();
		if(detail.getAttDate().startsWith("LEAVE")){
			showInfo(UIMessages.SELECT_ATTENDANCE_ENTRY_TO_MODIFY+". Selected entry is of type leave.");
			moveFocusToComp(displayTable);
			return;
		}
		
		if(showConfirmDialog(UIMessages.CONFIRM_DELETE))
			try {
//				attendanceDao.deleteAttEntry(employee.getEmpId(), detail.getRownum(), detail.getAttDate());
				
				attendanceDao.modifyAttendance(detail.getEid(), detail.getAttDate(), "00:00", 
						detail.getFirstLogin(), "00:00", false, detail.getRownum());
				
//				attendanceDao.updateLogOutStatus(employee.getEmpId(),detail.getAttDate());
				displayTable.getItems().remove(displayTable.getSelectionModel().getSelectedIndex());
				return;
			} catch (BusinessException e) {
				showError(UIMessages.ERROW_WHILE_DELETIN_ATTENDANCE);
			}
		displayTable.getSelectionModel().clearSelection();
	}

	public void goBack(ActionEvent event) {
	
		if (getParent() != null && getParent().length() > 0) {
			PayrollApplicationFactory.getMainController().showScreen(
					getParent(), false);
		}
	}

	public void modify() {
		
		if(mode.getSelectionModel().getSelectedIndex() != 0){
			showInfo(UIMessages.SELECT_DAILY_VIEW);
			moveFocusToComp(mode);
			return;
		}
		if(displayTable.getSelectionModel().getSelectedIndex() < 0){
			showInfo(UIMessages.SELECT_ATTENDANCE_ENTRY_TO_MODIFY);
			moveFocusToComp(displayTable);
			return;
		}
		AttendanceLeaveDetail detail  = displayTable.getSelectionModel().getSelectedItem();
		if(detail.getAttDate().startsWith("LEAVE")){
			showInfo(UIMessages.SELECT_ATTENDANCE_ENTRY_TO_MODIFY+". Selected entry is of type leave.");
			moveFocusToComp(displayTable);
			return;
		}

		String date = detail.getAttDate();
		String[] dateArrays = date.split("-");
		
		toAdd_year.getSelectionModel().select(dateArrays[2]);
		toAdd_Month.getSelectionModel().select(dateArrays[1]);
		toAdd_date.getSelectionModel().select(dateArrays[0]);
		
		inTime_toAdd.setDisable(false);
		outTime_toAdd.setDisable(false);
		firstIn_toAdd.setDisable(false);
		lastOut_toAdd.setDisable(false);
		
		inTime_toAdd.setText(detail.getFrom_time());
		outTime_toAdd.setText(detail.getTo_time());
		firstIn_toAdd.setSelected(detail.getFirstLogin());
		lastOut_toAdd.setSelected(detail.getLastLogOut());
		
		save.setDisable(false);
		cancel.setDisable(false);
		detailObjetAddOrMod = detail;
		moveFocusToComp(inTime_toAdd);
		modifyEntry  = true;
	}
	
	public void reset() {
		refreshUI();
	}

	public void getDetails(ActionEvent event) {
		
		
		displayTable.getItems().clear();
		String employeeId = empId.getText().trim().equals("") ? null : empId.getText().trim();
		int selectedMode = mode.getSelectionModel().getSelectedIndex();
		
		if(selectedMode < 0){
			showError(UIMessages.SELECT_MODE_OF_RETRIVAL);
			moveFocusToComp(mode);
			return;
		}
		if (selectedMode == 0) {
			if (employeeId == null || employeeId.equals("")) {
				moveFocusToComp(empId);
				showError (UIMessages.EMPLOYEE_ID_VALIDATION_MESSAGE);
				return;
			}
		}
		try {
			if(employeeId != null){
				
				PayRollUtility.validateEmpId(employeeId);
				employee = employeeDao.getEmpById(employeeId);
			}
		

		String validationMsg = getValidationMessage();
		if (!validationMsg.equals("")) {
			showError(validationMsg);
			return;
		}
		String fromDate = from_date.getSelectionModel()
				.getSelectedItem()
				+ "-"
				+ (from_month.getSelectionModel()
						.getSelectedIndex() + 1)
				+ "-"
				+ from_year.getSelectionModel()
						.getSelectedItem();

		String toDate = to_date.getSelectionModel().getSelectedItem()
				+ "-"
				+ (to_month.getSelectionModel()
						.getSelectedIndex() + 1) + "-"
				+ to_year.getSelectionModel().getSelectedItem();

		String departmentCode = department.getSelectionModel().getSelectedItem();
		String companyCode = companyBox.getSelectionModel().getSelectedItem();
		String unitCode = unitBox.getSelectionModel().getSelectedItem();
		if(departmentCode != null){
			departmentCode = departmentCode.substring(0,departmentCode.indexOf(":"));
		}
		if(companyCode != null){
			companyCode = companyCode.substring(0,companyCode.indexOf(":"));
		}
		
		if(unitCode != null){
			unitCode = unitCode.substring(0,unitCode.indexOf(":"));
		}
		attlevDetailList = attendanceDao.employeeTimesheetInfo(employeeId, companyCode, departmentCode, fromDate, toDate,unitCode, selectedMode);
		attLeaveList = AttendanceLeaveDetail.getAttendanceLeaveDetailList(attlevDetailList);
		displayTable.getItems().addAll(attLeaveList);
		
		if(employee != null){
			
			Add.setDisable(false);
			modify.setDisable(false);
			delete.setDisable(false);
		}
		} catch (Exception exception) {
			exception.printStackTrace();
			moveFocusToComp(empId);
			showError(exception.getMessage());
		}
	}
	
	public void cancel(){
		
		toAdd_year.getSelectionModel().clearSelection();
		toAdd_Month.getSelectionModel().clearSelection();
		toAdd_date.getSelectionModel().clearSelection();
		toAdd_date.getItems().clear();
		
		inTime_toAdd.clear();
		outTime_toAdd.clear();
		firstIn_toAdd.setSelected(false);
		lastOut_toAdd.setSelected(false);
		addEntry = false;
		modifyEntry = false;
	}
	@Override
	public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

		int year = PayRollUtility.getYear() - 1;
		for (int i = 0; i < 5; i++) {
			yearList.add(year + "");
			year++;
		}
		
		to_year.getItems().addAll(yearList);
		from_year.getItems().addAll(yearList);
		toAdd_year.getItems().addAll(yearList);
		
		
		iniTableProps();
		mode.getSelectionModel().selectedIndexProperty()
		.addListener(new ChangeListener<Number>() {

			@Override
			public void changed(ObservableValue arg0, Number arg1,
					Number arg2) {
				
				//TODO : Add after testing
				/*if(mode.getSelectionModel().getSelectedIndex() > 0)
					refreshUI();*/
			}

		});
		to_year.getSelectionModel().selectedIndexProperty()
				.addListener(new ChangeListener<Number>() {

					@Override
					public void changed(ObservableValue arg0, Number arg1,
							Number arg2) {
						
						to_month.getSelectionModel().clearSelection();
					}

				});
		
		toAdd_year.getSelectionModel().selectedIndexProperty()
		.addListener(new ChangeListener<Number>() {

			@Override
			public void changed(ObservableValue arg0, Number arg1,
					Number arg2) {
				
				toAdd_Month.getSelectionModel().clearSelection();
			}

		});
		
		to_month.getSelectionModel().selectedIndexProperty()
				.addListener(new ChangeListener<Number>() {

					@Override
					public void changed(ObservableValue arg0, Number arg1,
							Number arg2) {
						
						to_date.getSelectionModel().clearSelection();
						to_date.getItems().clear();
						toMonthDaysList.clear();
						
						if(to_month.getSelectionModel().getSelectedIndex()< 0)
							return;
						toMaxDay = PayRollUtility.getMaxDayofMonth(Integer
								.parseInt(to_year.getSelectionModel()
										.getSelectedItem()), to_month
								.getSelectionModel().getSelectedIndex());
						for (int i = 1; i <= toMaxDay; i++) {

							toMonthDaysList.add(i + "");
						}
						to_date.getItems().addAll(toMonthDaysList);
					}

				});
		
		toAdd_Month.getSelectionModel().selectedIndexProperty()
		.addListener(new ChangeListener<Number>() {

			@Override
			public void changed(ObservableValue arg0, Number arg1,
					Number arg2) {
				
				toAdd_date.getSelectionModel().clearSelection();
				toAdd_date.getItems().clear();
				toAddMonthDaysList.clear();
				
				if(toAdd_Month.getSelectionModel().getSelectedIndex()< 0)
					return;
				toAddMaxDay = PayRollUtility.getMaxDayofMonth(Integer
						.parseInt(toAdd_year.getSelectionModel()
								.getSelectedItem()), toAdd_Month
						.getSelectionModel().getSelectedIndex());
				for (int i = 1; i <= toAddMaxDay; i++) {

					toAddMonthDaysList.add(i + "");
				}
				toAdd_date.getItems().addAll(toAddMonthDaysList);
			}

		});
		
		from_year.getSelectionModel().selectedIndexProperty()
		.addListener(new ChangeListener<Number>() {

			@Override
			public void changed(ObservableValue arg0, Number arg1,
					Number arg2) {
				from_month.getSelectionModel().clearSelection();
			}

		});
		from_month.getSelectionModel().selectedIndexProperty()
				.addListener(new ChangeListener<Number>() {

					@Override
					public void changed(ObservableValue arg0, Number arg1,
							Number arg2) {

						from_date.getSelectionModel().clearSelection();
						from_date.getItems().clear();
						fromMonthDaysList.clear();
						
						if(from_month.getSelectionModel().getSelectedIndex()< 0)
							return;
						System.out.println(from_date.getItems());
						fromMaxDay = PayRollUtility.getMaxDayofMonth(Integer
								.parseInt(from_year.getSelectionModel()
										.getSelectedItem()), from_month
								.getSelectionModel().getSelectedIndex());
						for (int i = 1; i <= fromMaxDay; i++) {

							fromMonthDaysList.add(i + "");
						}
						from_date.getItems().addAll(fromMonthDaysList);

					}

				});
		
		
		
		companyBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {

			@Override
			public void changed(ObservableValue arg0, String arg1,
					String arg2) {

				try {
				department.getItems().clear();
				unitBox.getItems().clear();
				ArrayList<Department> departments;
					String companyCode = companyBox.getSelectionModel().getSelectedItem();
					if(companyCode == null){
						return;
					}
					PayRollUtility.debug("companyCode : "+companyCode);
					companyCode = companyCode.substring(0,companyCode.indexOf(":"));

					departments = (ArrayList<Department>) employeeDao.getAllDepartments(companyCode);
					
					Iterator<Department> departmentiIterator = departments.listIterator();
					while(departmentiIterator.hasNext()){
						Department dept = departmentiIterator.next();
						department.getItems().add(dept.getCode()+":"+dept.getDescription());
					}
					
					
					ArrayList<Units> unitList =  (ArrayList<Units>) employeeDao.getUnits(companyCode);
					Iterator<Units> unitListIterator = unitList.listIterator();
					while(unitListIterator.hasNext()){
						Units unit = unitListIterator.next();
						unitBox.getItems().add(unit.getUnitId()+":"+unit.getName());
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
		
		
	}

	@Override
	public Parent getView() {
		return grid;
	}

	@Override
	public String getTitle() {
		return UIMessages.UITitles.ATTENDANCE;
	}

	public void refreshUI(Object... args) {
		importFileLoc.clear();
		exportFileLoc.clear();
		
		if(args != null && args.length > 0){
			
			currCompany = (Company)args[0];
			if(args.length > 1 && args[1] instanceof UserAccounts){
				userAccounts = (UserAccounts)args[1];
			}
			mode.getSelectionModel().clearSelection();
		}	
		addEntry = false;
		modifyEntry = false;
		attlevDetailList = null;
		empId.clear();
		companyBox.getSelectionModel().clearSelection();
		department.getSelectionModel().clearSelection();
		unitBox.getSelectionModel().clearSelection();
		
		from_year.getSelectionModel().clearSelection();
		from_month.getSelectionModel().clearSelection();
		from_date.getSelectionModel().clearSelection();
		from_date.getItems().clear();
		
		to_year.getSelectionModel().clearSelection();
		to_month.getSelectionModel().clearSelection();
		to_date.getSelectionModel().clearSelection();
		to_date.getItems().clear();

		toAdd_year.getSelectionModel().clearSelection();
		toAdd_Month.getSelectionModel().clearSelection();
		toAdd_date.getSelectionModel().clearSelection();
		toAdd_date.getItems().clear();
		
		employee = null;
		displayTable.getItems().clear();
		
		inTime_toAdd.clear();
		outTime_toAdd.clear();
		firstIn_toAdd.setSelected(false);
		lastOut_toAdd.setSelected(false);
		
		
		Add.setDisable(true);
		modify.setDisable(true);
		delete.setDisable(true);
		
		enableDisableAdd(true);
		
		try{	
			
			ArrayList<Company> companyList =  (ArrayList<Company>) employeeDao.getCompanies();
			Iterator<Company> companyListIterator = companyList.listIterator();
			while(companyListIterator.hasNext()){
				Company comp = companyListIterator.next();
				companyBox.getItems().add(comp.getCompanyID()+":"+comp.getName());
			}
			
		}catch(Exception e){
			e.printStackTrace();
			showError(e.getMessage());
		}
	}
	
	public void goBack() {
		if (getParent() != null && getParent().length() > 0) {
			PayrollApplicationFactory.getMainController().showScreen(
					getParent(), false);
		}
	}
	
	@Override
	public String getValidationMessage() {
		
		String employeeId = empId.getText().trim().equals("") ? null : empId
				.getText().trim();

		if (mode.getSelectionModel().getSelectedIndex() == 0) {
			if (employeeId == null || employeeId.equals("")) {
				moveFocusToComp(empId);
				return (UIMessages.EMPLOYEE_ID_VALIDATION_MESSAGE);
			}
		}
		try {
			if(employeeId != null){
				
				PayRollUtility.validateEmpId(employeeId);
				employee = employeeDao.getEmpById(employeeId);
			}
		} catch (Exception exception) {
			moveFocusToComp(empId);
			return(exception.getMessage());
		}
		if (from_year.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.FROM_YEAR;
		}
		if (from_month.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.FROM_MONTH;
		}
		if (from_date.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.FROM_DAY;
		}
		if (to_year.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.TO_YEAR;
		}
		if (to_month.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.TO_MONTH;
		}
		if (to_date.getSelectionModel().getSelectedIndex() < 0) {
			return UIMessages.TO_DAY;
		}

		return "";

	}

	@Override
	public boolean isValid() {
		return false;
	}
	
	private void iniTableProps() {
		
		displayTable.setEditable(true);
		eid.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("eid"));
		empName.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("empName"));
		company.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("company"));
		deptCol.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("deptCol"));
		attDate.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("attDate"));
		from_time.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("from_time"));
		to_time.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("to_time"));
		total.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("total"));
		reson.setCellValueFactory(new PropertyValueFactory<AttendanceLeaveDetail, String>("reson"));
	}
	
	private void enableDisableAdd(boolean disabled){
		
		empId.setEditable(disabled);
		toAdd_year.setDisable(disabled);
		toAdd_Month.setDisable(disabled);
		toAdd_date.setDisable(disabled);
		inTime_toAdd.setDisable(disabled);
		outTime_toAdd.setDisable(disabled);
		firstIn_toAdd.setDisable(disabled);
		lastOut_toAdd.setDisable(disabled);
		cancel.setDisable(disabled);
		save.setDisable(disabled);
		
		
	}
	
	public void browseImport(){

		try{
			FileChooser fileChooser = new FileChooser(); 
			fileChooser.setTitle("Select Attendance File");

			File file = fileChooser.showOpenDialog(null);
			File destinationFile = new File(file.getAbsolutePath());
			String fileName = destinationFile.getName();
			if(file!=null && !file.isDirectory()){

				importFileLoc.setText(destinationFile.getAbsolutePath());
				if(fileName !=null && !fileName.equals(UIMessages.FileName.ATT_LIST)){
					showError("To import Attendance, Please select file having name  :"+UIMessages.FileName.ATT_LIST);
					refreshUI();
					return;
				}


				FileReader fr = new FileReader(file);

				BufferedReader br = new BufferedReader(fr);

				String colnms = br.readLine();
				if(colnms == null || colnms.equals("")){

					showError("No data in file : "+fileName);
					refreshUI();
					br.close();
					return;
				}


				String[] colArray = colnms.split(",");
				if(colArray == null || colArray.length != 6	){

					showError("Improper data in file : "+fileName+", Valid data must contain only \n"
							+ "EMPID,EmpName,Date(DD-MM-YYYY),IN(HH:MM),OUT(HH:MM),RowNum");
					br.close();
					refreshUI();
					return;
				}
				br.close();

			}else{
				showInfo("Export Operation cancelled as file not selected for import.");
				refreshUI();
				return;
			}

		}catch(Exception e){
			refreshUI();
			showError("Error while importing company data.");
		}
	}

	public void importSubmit(){

		try{

			File file = new File(importFileLoc.getText().trim());
			ArrayList<HashMap<String, String>> attInfoMap = new ArrayList<HashMap<String,String>>();
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String[] clnmsArray = br.readLine().split(",");
			String dataLine = null;
			while((dataLine = br.readLine()) != null){
				System.out.println("dataLine : "+dataLine);
				String[] data = dataLine.split(",");

				HashMap<String, String> cur = new HashMap<String, String>();
				for(int i= 0;i < data.length;i++){

					cur.put(clnmsArray[i],data[i].replaceAll("'", ""));
				}
				attInfoMap.add(cur);

			}

			System.out.println("attInfoMap : "+attInfoMap.size());
			Iterator<HashMap<String, String>> companyInfoMapIterator = attInfoMap.iterator();
			StringBuffer errorBuffer = new StringBuffer();
			while(companyInfoMapIterator.hasNext()){

				HashMap<String, String > current = companyInfoMapIterator.next();
				try{
					attendanceDao.addAttandeanceEntry(current.get("EMPID"), PayRollUtility.convertStringToDate(current.get("Date(DD-MM-YYYY)")), 
							current.get("IN(HH:MM)"), current.get("OUT(HH:MM)"), userAccounts.getUsername(), Integer.parseInt("RowNum"), true, true);
				}catch(Exception e){
					e.printStackTrace();
					errorBuffer.append("EMPID :"+current.get("EMPID")+", Date : "+current.get("Date(DD-MM-YYYY)")+"\n");
				}
			}

			if(!errorBuffer.toString().equals("")){
				showError("Failed to add attendance for following employees : \n"+errorBuffer);
			}

			refreshUI();
			br.close();
		}catch(Exception e){
			e.printStackTrace();
			refreshUI();
			showError("Error while importing attendance data.");
		}

	}

	public void browseExport(){

		try{
			DirectoryChooser fileChooser = new DirectoryChooser(); 
			fileChooser.setTitle("Select Destination");

			File file = fileChooser.showDialog(null);
			File destinationFile = new File(file.getAbsolutePath());
			if(file!=null && file.isDirectory()){

				exportFileLoc.setText(destinationFile.getAbsolutePath());

			}else{
				showInfo("Export Operation cancelled as Directry nor selected for export.");
				refreshUI();
				return;
			}

		}catch(Exception e){
			refreshUI();
			showError("Error while exporting company data.");
		}

	}
	public void exportSubmit(){
		try{

			File file = new File(exportFileLoc.getText()+"//"+UIMessages.FileName.ATT_LIST);
			FileWriter fw =new FileWriter(file,true);
			BufferedWriter bw =new BufferedWriter(fw);
			bw.write("EMPID,EmpName,Date(DD-MM-YYYY),IN(HH:MM),OUT(HH:MM),RowNum\n");
			getDetails(null);
			
			if(attlevDetailList != null){
				
				Iterator<HashMap<String, String>> attlevDetailListIterator = attlevDetailList.iterator();
				
				while(attlevDetailListIterator.hasNext()){
					
					HashMap<String, String> cur = attlevDetailListIterator.next();
					StringBuffer dataLine = new StringBuffer();
					dataLine.append(cur.get(CustomTableConstants.EMPI)).append(",");
					dataLine.append(cur.get(CustomTableConstants.name)).append(",");
					dataLine.append(cur.get(CustomTableConstants.from_time)).append(",");
					dataLine.append(cur.get(CustomTableConstants.to_time)).append(",");
					dataLine.append(cur.get(CustomTableConstants.rowNum));
					bw.write(dataLine.toString()+"\n");
				}
			}

			showInfo("Successfuly exported companies.");
			bw.flush();
			fw.flush();
			bw.close();fw.close();
		}catch(Exception e){
			e.printStackTrace();
			showError("Error while exporting company data.");
		}

	}
}
